<template>
    <el-card>
        <template #header>
            <h3>医疗器械管理<span v-if="this.institution">（{{ this.institution }}）</span></h3>
        </template>
        <!-- 搜索区域 -->
        <el-button type="primary" class="add" @click="showAddWindow()">添加医疗器械</el-button>
        <el-form inline>
            <el-form-item label="医疗器械名称" style="width: 200px">
                <el-autocomplete v-model="params.name" value-key="name" :fetch-suggestions="querySearch" clearable
                    class="inline-input w-50" placeholder="" @select="handleSelect" @input="clear" />
            </el-form-item>
            <el-form-item label="用途" style="width: 200px">
                <el-input v-model="params.description"></el-input>
            </el-form-item>
            <el-form-item label="最新维护日期" style="width: 250px">
                <el-date-picker v-model="params.last_maintenance_date" type="date" placeholder="选择日期"
                    style="width: 250px" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="params.status" placeholder="" style="width: 70px">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchDevices()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格区域 -->
        <el-table :data="devices" border @sort-change="handleSortChange">
            <!-- 扩展行 -->
            <el-table-column label="详情" type="expand" width="60">
                <template #default="props">
                    <el-descriptions class="margin-top" :column="1" border>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">用途：</div>
                            </template>
                            {{ props.row.description }}
                        </el-descriptions-item>
                    </el-descriptions>
                </template>
            </el-table-column>
            <el-table-column label="图片" align="center" width="200">
                <template #default="scope">
                    <el-image v-if="scope.row.device_img" :src="scope.row.device_img" class="row-device-img"></el-image>
                    <el-image v-else src="src\assets\imgs\暂无图片.png" class="row-device-img"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="医疗器械名称" prop="name" sortable="custom" align="center" width=""></el-table-column>
            <el-table-column label="最新维护日期" prop="last_maintenance_date" sortable="custom" align="center"
                width=""></el-table-column>
            <el-table-column label="状态" prop="status" sortable="custom" align="center" width="110">
                <template #default="scope">
                    <span v-if="scope.row.status == 0">正常</span>
                    <span v-else>维护中</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="190">
                <template #default="scope">
                    <el-button type="primary" @click="showEditWindow(scope.row)">修改维护</el-button>
                    <!-- 删除确认气泡 -->
                    <el-popconfirm width="250" icon-color="#626AEF" title="确认删除该医疗器械吗？">
                        <template #reference>
                            <el-button type="danger">删除</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                            <el-button size="small" @click.once="cancel">取消</el-button>
                            <el-button type="danger" size="small" @click.once="deleteDevice(scope.row, confirm)">
                                确认
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 医疗器械信息编辑弹窗 -->
    <el-dialog v-model="showEdit" title="医疗器械管理" width="500" @close="closeWindow">
        <el-form :model="row" label-width="120px" :rules="rules" ref="rowForm">
            <el-form-item label="添加医疗器械" prop="name" v-if="showAdd">
                <el-autocomplete v-model="row.name" value-key="name" :fetch-suggestions="querySearchAdd" clearable
                    class="inline-input w-50" placeholder="" @select="handleSelectAdd" @input="clearAdd" />
            </el-form-item>
            <el-form-item label="最新维护日期" prop="last_maintenance_date">
                <el-date-picker v-model="row.last_maintenance_date" type="date" placeholder="选择日期"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="row.status" placeholder="" style="width: 100px">
                    <el-option v-for="item in statusOptionsEdit" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-if="!showAdd" type="primary" @click="updateStock(row)">保存</el-button>
                <el-button v-if="showAdd" type="primary" @click="addDevice(row)">添加</el-button>
                <el-button @click="showEdit = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { institutionDeviceUpdateStockAPI } from '@/api/institutionDevice';
import { IDeviceAddAPI, IDeviceDeleteAPI, institutionDeviceFindByInstitutionIdAPI } from '@/api/institutionDevice';
import { deviceDropDownFindAPI, deviceDropDownWithoutFindAPI } from '@/api/medicalDevice';
import { ElMessage } from 'element-plus';
export default {
    data() {
        return {
            params: {
                // 搜索关键词
                institution_id: this.$route.params.id,
                name: '',
                description: '',
                status: '',
                last_maintenance_date: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7
            },
            devicesDropDown: [],
            devicesDropDownWithout: [],
            devices: [],
            institution: '',
            showEdit: false,
            showAdd: false,
            row: {},
            statusOptions: [
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: '0',
                    label: '正常'
                },
                {
                    value: '1',
                    label: '维护中'
                }
            ],
            statusOptionsEdit: [
                {
                    value: 0,
                    label: '正常'
                },
                {
                    value: 1,
                    label: '维护中'
                }
            ],
            rules: {
                name: { required: true, message: '医疗器械不能为空', trigger: 'change' },
                last_maintenance_date: { required: true, message: '最新维护日期不能为空', trigger: 'change' },
                status: { required: true, message: '状态不能为空', trigger: 'change' }
            },
        }
    },
    methods: {
        loadDeviceInfoList() {
            institutionDeviceFindByInstitutionIdAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    // resp.data.code.is_otc = resp.data.code.is_otc == true ? 1 : 0;
                    this.devices = resp.data.datas;
                    this.institution = resp.data.datas[0].institution;
                    this.params.total = resp.data.total;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        searchDevices() {
            this.loadDeviceInfoList();
        },
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadDeviceInfoList();
        },
        showEditWindow(row) {
            this.row = JSON.parse(JSON.stringify(row));
            this.showEdit = true;
        },
        updateStock(row) {
            this.$refs.rowForm.validate((val) => {
                if (val) {
                    institutionDeviceUpdateStockAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadDeviceInfoList();
                            this.showEdit = false;
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
        },
        deleteDevice(row, confirm) {
            IDeviceDeleteAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    this.loadDeviceInfoList();
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            confirm();
        },
        showAddWindow() {
            this.row = {};
            this.showEdit = true;
            this.showAdd = true;
        },
        addDevice(row) {
            this.$refs.rowForm.validate((val) => {
                if (val) {
                    this.row.institution_id = this.params.institution_id;
                    IDeviceAddAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadDeviceInfoList();
                            this.loadDropDownList();
                            this.showEdit = false;
                            this.showAdd = false;
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
        },
        closeWindow() {
            this.showEdit = false;
            this.showAdd = false;
        },
        //该方法选择列表后触发
        handleSelect(item) {
            this.params.device_id = item.id;
        },
        handleSelectAdd(item) {
            this.row.device_id = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearch(queryString, cb) {
            let results = this.devicesDropDown;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        querySearchAdd(queryString, cb) {
            let results = this.devicesDropDownWithout;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        //这是当输入数据时触发的，筛选出和输入数据匹配的建议输入。
        createFilter(queryString) {
            return (device) => {
                // 确保 institution 是一个字符串或对象
                if (typeof device === 'object') {
                    return JSON.stringify(device).toLowerCase().indexOf(queryString.toLowerCase()) > -1;
                }
                return device.toLowerCase().indexOf(queryString.toLowerCase()) > -1;
            };
        },
        //点击清除按钮时触发事件
        clear() {
            this.params.device_id = '';
        },
        clearAdd() {
            this.row.device_id = '';
        },
        loadDropDownList() {
            deviceDropDownFindAPI(this.$route.params.id).then((resp) => {
                if (resp.data.code == 2000) {
                    this.devicesDropDown = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            deviceDropDownWithoutFindAPI(this.$route.params.id).then((resp) => {
                if (resp.data.code == 2000) {
                    this.devicesDropDownWithout = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        handleSortChange({ prop, order }) {
            if (order) {
                // 根据 prop 和 order 进行排序
                this.params.sortProp = prop;
                this.params.sortOrder = order === 'ascending' ? 'asc' : 'desc';
                this.loadDeviceInfoList();
            } else {
                // 清除排序
                delete this.params.sortProp;
                delete this.params.sortOrder;
                this.loadDeviceInfoList();
            }
        }
    },
    created() {
        this.params.institution_id = this.$route.params.id;
        this.loadDeviceInfoList();
        this.loadDropDownList();
    }
}
</script>

<style scoped>
.el-pagination {
    margin: 20px 0 0 450px;
    align-items: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.row-device-img {
    width: 150px;
    height: 100px;
}

.device_img {
    width: 300px;
    height: 200px;
}

.add {
    position: relative;
    top: -10px;
}
</style>